package org.zhc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.zhc.constant.Constants;

/**
 * 编码格式过滤器
 * 
 * @author 张浩春
 * 
 */
public class EncodingFilter implements Filter {

	private String charset = Constants.DEFAULT_CHARSET;
	private static final Logger logger = Logger.getLogger(EncodingFilter.class
			.getName());

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse rep,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) rep;
		request.setCharacterEncoding(this.charset);
		response.setCharacterEncoding(this.charset);
		chain.doFilter(req, rep);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String charset = config.getInitParameter("charset");
		if (charset != null && !charset.trim().equals("")) {
			this.charset = charset;
		}
		logger.info("Current encoding is " + this.charset);
	}

}
